<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="BOM编码" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入BOM编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM版本" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入BOM版本"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['md:bom:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange" border>
      <el-table-column label="BOM编码" width="150" align="center" prop="bomCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['md:bom:query']"
          >{{scope.row.bomCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="BOM版本" align="center" prop="bomName" :show-overflow-tooltip="true"/>
      <el-table-column label="产品编码" width="140" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
      <el-table-column label="产品类别" align="center" prop="bomDefault" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.bomDefault === 0" type="success">成品</el-tag>
          <el-tag v-else>半成品</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="工艺路线编号" width="100" align="center" prop="routeCode" />
      <el-table-column label="工艺路线名称" align="center" prop="routeName" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bom_status_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" >
        <template slot-scope="scope">
          <!-- 草稿、待变更状态下按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:bom:edit']"
            v-if="scope.row.status === '草稿' || scope.row.status === '待变更'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['md:bom:edit']"
            v-if="scope.row.status === '草稿' || scope.row.status === '待变更'"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:bom:remove']"
            v-if="scope.row.status === '草稿' || scope.row.status === '待变更'"
          >删除</el-button>

<!--        <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh-left"
              @click="handleRefresh(scope.row)"
              v-hasPermi="['md:bom:edit']"
              v-if="scope.row.status === '失效'"
            >恢复</el-button>-->

          <!-- 发布状态下按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRemark(scope.row)"
            v-hasPermi="['md:bom:edit']"
            v-if="scope.row.status === '发布'"
          >备注</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleStop(scope.row)"
            v-hasPermi="['md:bom:edit']"
            v-if="scope.row.status === '发布'"
          >失效</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
            v-hasPermi="['md:bom:add']"
            v-if="scope.row.status === '发布'"
          >变更</el-button>

          <!-- 更多下拉菜单中按钮 -->
          <el-dropdown size="mini" trigger="click">
            <span class="el-dropdown-link" style="cursor: pointer;">
              <i class="el-icon-arrow-down el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                  v-hasPermi="['md:bom:query']"
                >查看</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status !== '草稿' && scope.row.status !== '待变更'">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="handleExport(scope.row)"
                  v-hasPermi="['md:bom:export']"
                >导出</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改BOM管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1330px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="BOM编码" prop="bomCode">
              <el-input v-model="form.bomCode" placeholder="请输入BOM编码" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)"
                         v-if="optType === 'add'"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类别" prop="bomDefault">
              <el-radio-group v-model="form.bomDefault">
                <el-radio :label="0" :disabled="form.status === '待变更'">成品</el-radio>
                <el-radio :label="1" :disabled="form.status === '待变更'">半成品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="itemCode">
              <el-input v-model="form.itemCode" readonly placeholder="请输入产品编码">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleSelectProduct"
                  v-if="optType === 'add'"
                  ></el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品物料名称" prop="itemName">
              <el-input v-model="form.itemName" readonly placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="图纸集版本" prop="drawCode">
              <el-input v-model="form.drawCode" readonly placeholder="请选择图纸版本">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleSelectDraw"
                  v-if="optType === 'add' || form.status === '待变更'"
                ></el-button>
              </el-input>
            </el-form-item>
            <DrawSelect ref="drawSelect" :itemCode="form.itemCode" @onSelected="onDrawSelected" > </DrawSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" readonly placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工艺路线编号" prop="routeCode">
              <el-input v-model="form.routeCode" readonly placeholder="请选择工艺路线">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleSelectRoute"
                  v-if="optType === 'add'"
                ></el-button>
              </el-input>
            </el-form-item>
            <RouteSelect ref="routeSelect" @onSelected="onRouteSelected" > </RouteSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺路线名称" prop="routeName">
              <el-input v-model="form.routeName" readonly placeholder="请输入工艺路线名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <el-tabs type="border-card" v-model="tabValues" v-if="form.bomId != null">
        <el-tab-pane label="BOM物料组成" name="bomItem">
          <BomItem :bomId="form.bomId" :itemCode="form.itemCode" :confirm="refresh"></BomItem>
        </el-tab-pane>
        <el-tab-pane label="BOM工序物料" name="routeItem">
          <el-tabs type="border-card">
            <el-tab-pane v-for="(process,index) in processOptions" :key="index" :label="process.processName">
              <RouteProductBom
                :routeId="form.routeId"
                :productId="form.itemId"
                :processId="process.processId"
                :bomId="form.bomId"></RouteProductBom>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="BOM工序图纸" name="processPicture">
          <el-tabs type="border-card">
            <el-tab-pane v-for="(process,index) in processOptions" :key="index" :label="process.processName">
              <ProcessPicture
                :processId="process.processId"
                :routeId="form.routeId"
                :bomId="form.bomId"
                :drawCode="form.drawCode"></ProcessPicture>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情页面 -->
    <el-dialog :title="title" :visible.sync="viewOpen" width="1350px">
      <el-descriptions :column="2" style="margin-bottom: 40px;" border>
        <el-descriptions-item
          label="BOM版本："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.bomName }}</el-descriptions-item>
        <el-descriptions-item
          label="产品："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.itemName }}</el-descriptions-item>
        <el-descriptions-item
          label="创建人："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.createBy }}</el-descriptions-item>
        <el-descriptions-item
          label="创建时间："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.createTime }}</el-descriptions-item>
        <el-descriptions-item
          label="最后操作人："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.updateBy }}</el-descriptions-item>
        <el-descriptions-item
          label="最后操作时间："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.updateTime }}</el-descriptions-item>
        <el-descriptions-item
          label="备注："
          label-style="margin-bottom: 20px; margin-top: 20px;"
          content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-row>
        <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
          <el-tab-pane v-for="item in dicList" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
        </el-tabs>
        <div class="mod-config" style="width: 100%;">

          <!-- 基本信息 -->
          <div v-show="isBase">
            <el-descriptions :column="2" style="margin-top: 40px;" border>
              <el-descriptions-item
                label="BOM编号"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.bomCode }}</el-descriptions-item>
              <el-descriptions-item
                label="BOM版本"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.bomName }}</el-descriptions-item>
              <el-descriptions-item
                label="图纸集版本"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">
                {{ viewData.drawCode }}
<!--                <el-button type="text" v-if="viewData.drawCode != null" @click="drawView">查看</el-button>-->
              </el-descriptions-item>
              <el-descriptions-item
                label="产品名称"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.itemName }}</el-descriptions-item>
              <el-descriptions-item
                label="产品编码"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.itemCode }}</el-descriptions-item>
              <el-descriptions-item
                label="单位"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.unitOfMeasure }}</el-descriptions-item>
              <el-descriptions-item
                label="规格型号"
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ viewData.specification }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 物料组成 -->
          <div v-show="isItem">
            <el-table :data="itemList" style="margin-top: 20px;" border>
              <el-table-column label="序号" align="center" prop="sort" width="50" v-if="displaySort" />
              <el-table-column label="物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
              <el-table-column label="物料编号" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
              <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
              <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
              <el-table-column label="图纸编号" align="center" prop="drawCode" :show-overflow-tooltip="true"/>
              <el-table-column label="使用量" align="center" prop="used" />
              <el-table-column label="规格" align="center" prop="model" :show-overflow-tooltip="true"/>
              <el-table-column label="规格单位" align="center" prop="specificationUnit"/>
              <el-table-column label="重量（kg）" align="center" prop="weight" />
            </el-table>
            <pagination
              v-show="itemTotal>0"
              :total="itemTotal"
              :page.sync="itemQueryParams.pageNum"
              :limit.sync="itemQueryParams.pageSize"
              @pagination="getBomItemList"
            />
          </div>

          <!-- BOM结构 -->
          <div v-show="isBom">
            <el-table
              v-if="refreshTable"
              v-loading="treeLoading"
              :data="treeList"
              row-key="_uniqueId"
              :default-expand-all="true"
              border
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <el-table-column
                label="产品/物料名称"
                width="180"
                align="left"
                prop="itemName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="产品/物料编号"
                width="140"
                align="center"
                prop="itemCode"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="物料类型" width="80" align="center" prop="itemType" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemType" />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true" />
              <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true" />
              <el-table-column label="bom编号" width="160" align="center" prop="bomCode" :show-overflow-tooltip="true" />
              <el-table-column label="bom版本" width="80" align="center" prop="bomName" :show-overflow-tooltip="true" />
              <el-table-column label="图纸编号" width="160" align="center" prop="drawCode" :show-overflow-tooltip="true"/>
              <el-table-column label="使用量" align="center" prop="used" />
              <el-table-column label="规格" align="center" prop="model" :show-overflow-tooltip="true"/>
              <el-table-column label="规格单位" align="center" prop="specificationUnit"/>
              <el-table-column label="重量（kg）" width="90" align="center" prop="weight" />
            </el-table>
            </div>

          <div v-show="isCharts" class="isCharts" style="width: 100%;">
            <ECharts :options="chartsList"></ECharts>
          </div>

          <!-- 工艺路线 -->
          <div v-show="isRoute">
            <el-descriptions :column="2" style="margin-top: 20px;" border >
              <el-descriptions-item
                label="工艺路线名称："
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ routeData.routeName }}</el-descriptions-item>
              <el-descriptions-item
                label="工艺路线编号："
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ routeData.routeCode }}</el-descriptions-item>
            </el-descriptions>
            <el-tabs type="border-card">
              <el-tab-pane v-for="(process,index) in processOptions" :key="index" :label="process.processName">
                <RouteProductBom
                  :routeId="process.routeId"
                  :productId="viewData.itemId"
                  :processId="process.processId"
                  :bomId="viewData.bomId"
                  :optType="optView"
                  :num="num"
                ></RouteProductBom>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 工序图纸 -->
          <div v-show="isPicture">
            <el-descriptions :column="2" style="margin-top: 20px;" border >
              <el-descriptions-item
                label="工艺路线名称："
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ routeData.routeName }}</el-descriptions-item>
              <el-descriptions-item
                label="工艺路线编号："
                label-style="margin-bottom: 20px; margin-top: 20px;"
                content-style="margin-bottom: 20px; margin-top: 20px;">{{ routeData.routeCode }}</el-descriptions-item>
            </el-descriptions>
            <el-tabs type="border-card">
              <el-tab-pane v-for="(process,index) in processOptions" :key="index" :label="process.processName">
                <PDFView
                  :processId="process.processId"
                  :bomId="viewData.bomId"></PDFView>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 成本估算 -->
        <div v-show="isCost">
          <el-descriptions :column="3" style="margin-top: 20px;" border >
            <el-descriptions-item
              label="总成本（元）："
              label-style="margin-bottom: 20px; margin-top: 20px; color: black;"
              content-style="margin-bottom: 20px; margin-top: 20px; color: red; font-weight: bolder;">{{ totalCost }} </el-descriptions-item>
            <el-descriptions-item
              label="物料成本（元）："
              label-style="margin-bottom: 20px; margin-top: 20px; color: black;"
              content-style="margin-bottom: 20px; margin-top: 20px; color: red; font-weight: bolder;">{{ itemCost }}</el-descriptions-item>
            <el-descriptions-item
              label="工序成本（元）："
              label-style="margin-bottom: 20px; margin-top: 20px; color: black;"
              content-style="margin-bottom: 20px; margin-top: 20px; color: red; font-weight: bolder;">{{ processCost }}</el-descriptions-item>
          </el-descriptions>
          <el-divider content-position="center" class="custom-divider">物料成本明细</el-divider>
          <el-table :data="costList.items" style="margin-top: 20px;" border>
            <el-table-column label="物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
            <el-table-column label="物料编号" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
            <el-table-column label="使用量" align="center" prop="used" />
            <el-table-column label="单价（元）" align="center" prop="referencePrice" />
            <el-table-column label="成本金额（元）" align="center" prop="total" />
          </el-table>
          <el-divider content-position="center" class="custom-divider">工序成本明细</el-divider>
          <el-table :data="costList.process" style="margin-top: 20px;">
            <el-table-column label="工序名称" align="center" prop="processName" :show-overflow-tooltip="true"/>
            <el-table-column label="计价类型" align="center" prop="pricingMethod">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.pro_pricing_method" :value="scope.row.pricingMethod"/>
              </template>
            </el-table-column>
            <el-table-column label="成本金额（元）" align="center" prop="price" />
          </el-table>
        </div>

      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleTabCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span style="color: red;">仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看图纸 -->
    <el-dialog :visible.sync="drawOpen" width="1200px" append-to-body>
      <iframe
        :src="drawUrl"
        frameborder="0"
        scrolling="auto"
        style="width: 100%; height: 600px;"
      />
    </el-dialog>

    <!-- 备注弹框 -->
    <el-dialog title="修改备注" :visible.sync="remarkOpen" width="600px" append-to-body>
      <el-input label="备注" v-model="remarkData.remark" type="textarea" rows="5"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemark">确 定</el-button>
        <el-button @click="cancelRemark">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listBomGl,
  getBomGl,
  delBomGl,
  addBomGl,
  updateBomGl,
  updateStatus,
  getCost,
  copyBom
} from "@/api/mes/md/bomgl";
import { listItem, listTree, getConfirmItem } from "@/api/mes/md/bomItem";
import { getProroute, getRouteByItem } from "@/api/mes/pro/proroute";
import { listProcess } from "@/api/mes/pro/routeprocess";
import { genCode } from "@/api/system/autocode/rule";
import { listRouteproductbom } from '@/api/mes/pro/routeproductbom';
import ItemSelect  from "./itemSelect.vue";
import BomItem from "./bomItem";
import RouteProductBom from './routeproductbom';
import ProcessPicture from "./processPicture";
import PDFView from "./pdfView";
import DrawSelect from "./drawSelect";
import {getToken} from "@/utils/auth";
import ECharts from "./echarts.vue";
import RouteSelect from "./routeSelect";

export default {
  name: "BomGL",
  dicts: ['bom_default', 'mes_item_product', 'bom_status_type', 'pro_pricing_method' ],
  components: {
    ItemSelect,
    BomItem,
    RouteProductBom,
    ProcessPicture,
    PDFView,
    DrawSelect,
    ECharts,
    RouteSelect,
  },
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM管理表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
        bomName: null,
        itemCode: null,
        itemName: null,
        routeCode: null,
        routeName: null,
        ancestors: '0',
      },
      // 表单参数
      form: {},
      // 详情数据
      viewData: {},
      // 标签属性
      tabValue: '0',
      // tab标签组
      dicList: [
        { label: "基本信息", value: '0' },
        { label: "物料组成", value: '1' },
        { label: "BOM结构", value: '2' },
        { label: "工艺路线", value: '3' },
        { label: "工序图纸", value: '4' },
        { label: "成本估算", value: '5' },
        { label: "结构树图", value: '6' },
      ],
      // 基本信息开关
      isBase: false,
      // 物料组成开关
      isItem: false,
      // BOM结构开关
      isBom: false,
      // 工艺路线开关
      isRoute: false,
      // 工艺图纸开关
      isPicture: false,
      // 成本估算开关
      isCost: false,
      // 结构树图开关
      isCharts: false,
      // 成本表格数据
      costList: [],
      // 物料总成本
      itemCost: 0,
      // 工序总成本
      processCost: 0,
      // 总成本
      totalCost: 0,
      // 物料表格数据
      itemList: [],
      // 物料总条数
      itemTotal: 0,
      itemQueryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
      },
      // 重新渲染表格状态
      refreshTable: true,
      // BOM结构
      treeLoading: true,
      // BOM结构数据
      treeList: [],
      // 工艺路线数据
      routeData: {},
      // 工艺步骤index值
      activeRoute: 0,
      // 工序列表
      processOptions: [],
      // 工序展示开关
      optView: 'view',
      // BOM物料开关
      tabValues: 'bomItem',
      // 工艺物料回显开关
      refresh: false,
      // 计数
      num: 0,
      // 表单校验
      rules: {
        bomCode: [
          { required: true, message: "BOM编码不能为空", trigger: "blur" }
        ],
        bomName: [
          { required: true, message: "BOM名称不能为空", trigger: "blur" }
        ],
        bomDefault: [
          { required: true, message: "产品类别不能为空", trigger: "change"}
        ],
        itemCode: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],
        routeCode: [
          { required: true, message: "工艺路线编号不能为空", trigger:"blur" }
        ],
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/md/bom/importData"
      },
      drawUrl: null,
      drawOpen: false,
      chartsList: [],
      optType: null,
      futureDatePickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now();
        },
      },
      // 修改备注开关
      remarkOpen: false,
      // 备注数据
      remarkData: {},
      // 序号显示开关
      displaySort: this.getDisplaySort(),
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询BOM管理列表 */
    getList() {
      this.loading = true;
      listBomGl(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bomId: null,
        bomCode: null,
        bomName: null,
        bomDefault: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        routeId: null,
        routeCode: null,
        routeName: null,
        drawCode: null,
        ancestors: "0",
        status: "草稿",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bomId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.optType = 'add';
      this.title = "添加BOM管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getConfirmItem(row.bomId);
      this.reset();
      const bomId = row.bomId || this.ids
      getBomGl(bomId).then(response => {
        this.form = response.data;
        this.open = true;
        this.optType = 'edit';
        this.title = "修改BOM管理";
        if (row.status === '待变更') {
          this.title = 'BOM管理变更'
        }
        this.tabValues = 'bomItem';
        this.getProcess();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.bomId != null) {
            updateBomGl(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBomGl(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bomIds = row.bomId || this.ids;
      this.$modal.confirm('是否确认删除BOM编号为"' + row.bomCode + '"的数据？').then(function() {
        return delBomGl(bomIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      let data = {bomId: row.bomId}
      this.download('md/bom/exportBom', data , row.itemName + `_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('BOM_CODE').then(response =>{
          this.form.bomCode = response;
        });
      }else{
        this.form.bomCode = null;
      }
    },
    // 产品物料选择开关
    handleSelectProduct(){
      this.$refs.itemSelect.showFlag = true;
    },
    // 产品物料选择弹出框
    onItemSelected(obj){
      if(obj !== undefined && obj !== null){
        /*if (obj.itemId !== null && obj.itemId !== undefined) {
          getRouteByItem(obj.itemId).then(response => {
            if (response.data !== null && response.data !== undefined) {
              this.form.routeId = response.data.routeId;
              this.form.routeCode = response.data.routeCode;
              this.form.routeName = response.data.routeName;
            }
          }).catch(() => {
            this.form.routeId = null;
            this.form.routeCode = null;
            this.form.routeName = null;
            this.$modal.msgError("请先维护工艺路线！");
          });
        }*/
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      this.num = this.num +1;
      const bomId = row.bomId
      getBomGl(bomId).then(response => {
        this.viewData = response.data;
        this.viewOpen = true;
        this.optType = 'view';
        this.title = "BOM详情";
        this.tabValue = '0';
        this.isBase = true;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = false;
      });
    },
    // 查看取消按钮
    handleTabCancel() {
      this.viewOpen = false;
      this.tabValue = '0';
    },
    // tab点击
    handleTabClick(tab, event) {
      if (tab.name === '1') {
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = true;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = false;
        this.getBomItemList();
      }else if(tab.name === '2') {
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = false;
        this.isBom = true;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = false;
        this.getTree();
      }else if (tab.name === '3') {
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = true;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = false;
        this.getRoute();
        this.getProcess();
      }else if (tab.name === '0') {
        this.tabValue = tab.name;
        this.isBase = true;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = false;
      }else if (tab.name === '4') {
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = true;
        this.isCost = false;
        this.isCharts = false;
        this.getRoute();
        this.getProcess();
      }else if (tab.name === '5') {
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = true;
        this.isCharts = false;
        this.handleCost();
      }else if (tab.name === '6'){
        this.tabValue = tab.name;
        this.isBase = false;
        this.isItem = false;
        this.isBom = false;
        this.isRoute = false;
        this.isPicture = false;
        this.isCost = false;
        this.isCharts = true;
        this.getTree();
      }
    },
    // 获取物料组成列表
    getBomItemList() {
      this.itemQueryParams.parentId = this.viewData.bomId;
      listItem(this.itemQueryParams).then(response => {
        this.itemList = response.rows;
        this.itemTotal = response.total;
      });
    },
    // 根据bomID获取树形结构
    getTree() {
      let bomId = this.viewData.bomId;
      listTree(bomId).then(response => {
        let list = response.data;

        // 构建树形结构
        let treeData = this.handleTree(list, 'bomId', 'parentId');

        // 深度克隆树结构，避免引用问题
        const deepCloneTree = (nodes) => {
          if (!nodes || !Array.isArray(nodes)) return [];

          return nodes.map(node => {
            const newNode = { ...node };
            if (newNode.children && newNode.children.length > 0) {
              newNode.children = deepCloneTree(newNode.children);
            }
            return newNode;
          });
        };

        // 克隆树结构
        let clonedTreeData = deepCloneTree(treeData);

        // 为克隆后的树形结构添加唯一ID
        const addUniqueIds = (() => {
          let counter = 0;
          return (nodes) => {
            nodes.forEach(node => {
              // 为每个节点生成全局唯一的ID
              node._uniqueId = `unique_${Date.now()}_${counter++}_${Math.random()}`;
              if (node.children && node.children.length > 0) {
                addUniqueIds(node.children);
              }
            });
          };
        })();

        addUniqueIds(clonedTreeData);

        this.treeList = clonedTreeData;

        // 处理chartsList
        list.some(e => {
          e.name = e.itemCode + '@' + e.itemName
        })
        this.chartsList = this.handleTree(list, 'bomId', 'parentId');
        this.treeLoading = false;
      })
    },
    // 获取工艺路线信息
    getRoute() {
      let routeId = this.viewData.routeId;
      getProroute(routeId).then(response => {
        this.routeData = response.data;
      });
    },
    //获取当前产品对应的生产工序
    getProcess(){
      let routeId = this.viewData.routeId || this.form.routeId;
      listProcess(routeId).then(response =>{
        this.processOptions = response.data;
      });
    },
    // BOM发布
    handleConfirm(row) {
      let params = {bomId: row.bomId, routeId: row.routeId}
      listRouteproductbom(params).then(response =>{
        if (response.total > 0) {
          this.$modal.confirm('是否发布BOM编号为"' + row.bomCode + '"的数据？发布后不可更改！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = { bomId: row.bomId, status: '发布' };
            updateStatus(data).then(response => {
              this.$modal.msgSuccess("发布成功！");
              this.getList();
            });
          }).catch(() => {});
        }else {
          this.$modal.msgError("请先维护BOM、工序物料！");
        }
      })
    },
    // BOM失效
    handleStop(row) {
      this.$modal.confirm('是否确认BOM编号为"' + row.bomCode + '"的数据失效？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { bomId: row.bomId, status: '失效' };
        updateStatus(data).then(response => {
          this.$modal.msgSuccess("成功失效！");
          this.getList();
        })
      }).catch(() => {
        this.$modal.msgError("取消失效！");
        return false;
      });
    },
    // BOM恢复
    handleRefresh(row) {
      this.$modal.confirm('是否恢复BOM编号为"' + row.bomCode + '"的数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { bomId: row.bomId, status: '发布' };
        updateStatus(data).then(response => {
          this.$modal.msgSuccess("恢复成功！");
          this.getList();
        })
      }).catch(() => {
        this.$modal.msgError("取消恢复！");
        return false;
      });
    },
    // 获取BOM物料确认信息
    getConfirmItem(bomId) {
      getConfirmItem(bomId).then(res => {
        this.refresh = res.rows.length > 0;
      })
    },
    // 图纸选择开关
    handleSelectDraw() {
      if (this.form.itemCode != null) {
        this.$refs.drawSelect.showFlag = true;
      }else {
        this.$modal.msgError("请先选择产品！");
      }
    },
    // 图纸回显
    onDrawSelected(obj) {
      if(obj !== undefined && obj !== null){
        this.form.drawCode = obj.itemName + '-' + obj.version;
      }
    },
    // 查询成本估算
    handleCost() {
      getCost(this.viewData.bomId, this.viewData.routeId).then(res => {
        this.costList = res.data;
        // 计算物料成本
        this.itemCost = 0;
        res.data.items.some(item => {
          this.itemCost = Math.round((this.itemCost + item.total) * 100) / 100;
        })
        // 计算工序成本
        this.processCost = 0;
        res.data.process.some(item => {
          this.processCost = Math.round( (this.processCost + item.price) * 100 ) / 100;
        })
        // 计算总成本
        this.totalCost = Math.round((this.itemCost + this.processCost) * 100) / 100;
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;color: red;'>"
        + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "BOM导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('md/bom/importTemplate', {}, `BOM导入模板.xlsx`)
    },
    drawView() {
      this.drawOpen = true;
      this.drawUrl = this.viewData.drawUrl;
    },
    // 工艺路线选择开关
    handleSelectRoute() {
      this.$refs.routeSelect.showFlag = true;
    },
    // 工艺路线回显
    onRouteSelected(obj) {
      if(obj !== undefined && obj !== null){
        this.form.routeId = obj.routeId;
        this.form.routeCode = obj.routeCode;
        this.form.routeName = obj.routeName;
      }
    },
    // 变更BOM
    handleCopy(row) {
      this.$modal.confirm('是否变更BOM编号为"' + row.bomCode + '"的数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        copyBom(row).then(response => {
          this.$modal.msgSuccess("变更成功！");
          this.getList();
        })
      }).catch(() => {
        this.$modal.msgError("取消变更！");
        return false;
      });
    },
    // 备注按钮点击
    handleRemark(row) {
      this.remarkOpen = true;
      this.remarkData = row;
    },
    // 提交变更备注
    submitRemark() {
      updateBomGl(this.remarkData).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.remarkOpen = false;
        this.getList();
      });
    },
    // 取消变更备注
    cancelRemark() {
      this.remarkOpen = false;
      this.reset();
    },
    // 获取环境变量并转为布尔值
    getDisplaySort() {
      return process.env.VUE_APP_DISPLAY_COLUMN_SWITCH === 'true';
    },


  }
};
</script>
<style scoped>
.custom-divider ::v-deep .el-divider__text {
  background-color: #fff;
  color: #409EFF;
  padding: 4px 12px;
  border-radius: 8px;
  border: 1px solid #409EFF;
}
.custom-divider{
  background-color: #409EFF;
}
</style>
